const baseURL = 'https://apifoxmock.com/m1/3787601-0-default'

const httpInterceptor = {
  invoke(options) {
    if (options.showToast !== false) {
      uni.showLoading({ title: '加载中', mask: true })
    }

    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    options.timeout = 10000
    options.header = {
      ...options.header
    }
  }
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

const request = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success(res) {
        if (res.data.code >= 200 && res.data.code < 300) {
          resolve(res.data)
        } else if (res.data.code === 401) {
          uni.navigateTo({ url: '/pages/login/index' })
          reject(res.data.msg)
        } else {
          uni.showToast({
            icon: 'none',
            title: res.data.msg || '请求错误'
          })
          reject(res)
        }
      },
      fail(err) {
        uni.showToast({ icon: 'none', title: '网络错误，换个网络试试' })
        reject(err)
      },
      complete() {
        if (options.showToast !== false) {
          uni.hideLoading()
        }
      }
    })
  })
}

export default request
